package com.dkm.ec.activity.schedler;

import com.dkm.ec.activity.persistence.entity.SecSkillActivitySkuPo;
import com.dkm.ec.activity.repository.SecSkillActivitySkuRepository;
import com.dkm.ec.activity.repository.TScheduleLockRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by fanjinyuan on 2017/8/18.
 */
public class SecKillActivityTimer extends Thread{

    private static final Logger LOG = LoggerFactory.getLogger(SecKillActivityTimer.class);
    private static final String SECKILL_ACTIVITY_LOCK_KEY = "seckill_act_sheduler_lock";
    private static final long sleepTime = 60*1000;
    private TScheduleLockRepository scheduleLockRepository;
    private SecSkillActivitySkuRepository secSkillActivitySkuRepository;

    @Override
    public void run(){
        while(!Thread.interrupted()){
            // 获取需要返回库存的sku
            List<SecSkillActivitySkuPo> needReturnStockSkus = secSkillActivitySkuRepository.findNeedReturnStockSkus();
            if(needReturnStockSkus != null && needReturnStockSkus.size() > 0) {
                LOG.debug("扫描到 {} 个秒杀活动已过期，归还库存任务开始", needReturnStockSkus.size());
                Boolean hasLock =false;
                try {
                    // 通过key获取锁
                    hasLock =scheduleLockRepository.getLock(SECKILL_ACTIVITY_LOCK_KEY);
                    if(hasLock){
                        LOG.debug("秒杀活动任务调度锁，开始任务");
                        // 归还库存
                        secSkillActivitySkuRepository.returnStock(needReturnStockSkus);
                    }
                }finally {
                    if(hasLock) {
                        LOG.debug("任务完毕，秒杀活动任务调度锁");
                        // 释放锁
                        scheduleLockRepository.unLock(SECKILL_ACTIVITY_LOCK_KEY);
                    }
                }
            }

            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }

    public void setScheduleLockRepository(TScheduleLockRepository scheduleLockRepository) {
        this.scheduleLockRepository = scheduleLockRepository;
    }

    public void setSecSkillActivitySkuRepository(SecSkillActivitySkuRepository secSkillActivitySkuRepository) {
        this.secSkillActivitySkuRepository = secSkillActivitySkuRepository;
    }
}
